package algocasts;

import java.util.LinkedList;
import java.util.Queue;

public class P16_minDepth {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
    }

    public int minDepth_Recursive(TreeNode root) {
        if (root == null) return 0;
        if (root.left == null && root.right == null) return 1;
        if (root.left == null) return minDepth_Recursive(root.right) + 1;
        if (root.right == null) return minDepth_Recursive(root.left) + 1;
        return Math.min(minDepth_Recursive(root.left), minDepth_Recursive(root.right));
    }

    public int minDepth_Iterative(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int depth = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left == null && node.right == null) return depth;
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            ++depth;
        }
        return depth;
    }
}
